18. Exercise: Add LiveData Encapsulation to GameViewModel

L5 26 Encapsulation In ViewModels SC

Now it’s your turn to complete this exercise yourself.

Let's encapsulate our variables as LiveData in GameViewModel. The point of this exercise is to not expose MutableLiveData outside of the view model.

1. Make internal and external versions of word and score:

Open up GameViewModel. The internal version should be a MutableLiveData, have an underscore in front of its name, and be private. The underscore is our convention for marking the variable as the internal version of a variable.

The external version should be a LiveData and not have an underscore in front of its name.

For example, here’s the internal and external version of score:

// internal
private val _score = MutableLiveData<Int>()
//external
val score: LiveData<Int>

2. Make a backing property for the external version that returns the internal MutableLiveData as a LiveData:

Kotlin automatically makes getters and setters for your fields. If you want to override the getter for score, you can do so using a backing property. You've actually already defined your backing properties (_score and _word). Now you can take your public versions of the variables (score and word) and override get to return the backing properties.

For example, here’s the full encapsulated score:

private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
    get() = _score

By making the return type LiveData rather than MutableLiveData, you've exposed only score and word as LiveData.

3. In the view model, use the internal, mutable versions of score and word:

In GameViewModel, update the code so that you use the mutable versions, _score and _word, throughout the view model. When you’re finished, make sure to run your code!

If you want to start at this step, you can download this exercise code from: Step.04-Exercise-Add-LiveData-Encapsulation.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.04-Solution-Add-LiveData-Encapsulation or using this git diff.

Task Description:

Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

You've encapsulated your LiveData for score and word! You can check your solution against the solution we’ve provided here Step.04-Solution-Add-LiveData-Encapsulation or using this git diff.